package com.hava.jdbc;

import java.sql.*;

/**
 * Created by zhanpeng on 2016/9/21.
 */
public class HelloJDBC {

    static final String JDBC_DRIVER = "org.postgresql.Driver";
//    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

    static final String DB_URL = "jdbc:postgresql://192.168.1.200/test";

    static final String USER = "postgres";

    static final String PASSWORD = "";

    public static void helloworld() throws ClassNotFoundException {

        Connection connection = null;

        Statement statement = null;

        ResultSet resultSet = null;


        // 1. add Driver
        Class.forName(JDBC_DRIVER);

        // 2. create db connnection
        try {
            connection = DriverManager.getConnection(DB_URL,USER,PASSWORD);
            System.out.println("getConnection");

            // 3.run SQL
            statement = connection.createStatement();
            resultSet = statement.executeQuery("SELECT \"userName\" FROM \"public\".\"user\"");

            // 4.get userName
            while(resultSet.next())
            {
                Integer index = resultSet.getRow();
                String value = resultSet.getString("userName");
                System.out.println("resultSet [row]:" + index + " [value]:" + value);
            }
        } catch (SQLException e) {
            // Exception
            e.printStackTrace();
        } finally {
            try {

                // 5. close connection
                if(connection != null)
                    connection.close();
                if(statement != null)
                    statement.close();
                if(resultSet != null)
                    resultSet.close();

                } catch (SQLException e) {
                    e.printStackTrace();
                }
        }
    }
}
